<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
    </theme-navbar>
    <!-- #endif -->

    <view class="content u-page" :style="`padding-bottom: ${isOperateAuth ? 140 : 2}rpx; min-height: calc(100% - ${isOperateAuth ? 140 : 2}rpx);`">

      <view
        class="card"
        v-for="(item) in retailerList"
        :key="item.retailerUuid"
      >
        <client-item :client="item"></client-item>
      </view>

      <!-- 派发/转办阶段展示 -->
      <template v-if="['02'].indexOf(formData.taskStatus) > -1">
        <view class="card" style="display: flex; align-items: center;">
          <view style="font-size: 30rpx; font-weight: 600; margin-right: 16rpx">
            任务紧急程度
          </view>

          <view style="margin: 15rpx 0;">
            <u-tag
              :text="allTaskUrgencyLevel[formData.taskUrgencyLevel]"
              style="margin-right: 20rpx; padding: 12rpx 35rpx; font-size: 28rpx;"
              ></u-tag>
          </view>
        </view>

        <view class="card">
          <view
            class="group-tag"
            v-for="(item, index) of coordTypeList"
            :key="index"
          >
            <view class="group-name">{{ item.coordTypeName }}</view>
            <view class="group-tag-list">
              <u-tag
                v-for="tagItem of item.tags.filter(item => !!item)"
                :text="tagItem.text"
                :key="tagItem.value"
                style="margin: 0 20rpx 20rpx 0; padding: 18rpx 22rpx; font-size: 28rpx;"
              />
            </view>
          </view>
        </view>

        <view class="card" style="padding-top: 25rpx; padding-bottom: 25rpx;">
          <view style="font-weight: 600;">备注说明</view>
          <view style="margin-top: 10rpx;">
            <!-- {{ formData.taskNote }} -->
            <u-input type="textarea" v-model="formData.taskNote" disabled />
          </view>
          <view style="margin-top: 15rpx;">
            <!-- <u-image v-for="item of filePath" width="150rpx" height="150rpx" :src="item.src" :key="item.fileId"></u-image> -->
            <upload-images
              :canAdd="false"
              :canDel="false"
              :url="uploadFile"
              :length="10"
              :extForm="{fiGroupCode: $FILE_GROUP_TYPE.three_teamwork_img, bizId: formData.taskUuid}"
              :bizId="formData.taskUuid"
              :del-url="delUrl"
              :can-add="true"
              :can-del="true"
              :renderImages="getImages($FILE_GROUP_TYPE.three_teamwork_img)"
              style="padding-left: 0;"
            ></upload-images>
          </view>

        </view>
      </template>

      <!-- 发起信息 -->
      <u-card v-if="['03', '04', '05', '06', '07'].indexOf(formData.taskStatus) > -1" title="发起信息" style="margin-left: 0; margin-right: 0;">
        <view slot="body">
          
          <u-form>
            <u-form-item label="任务紧急程度" label-width="auto">
              <text>{{ allTaskUrgencyLevel[formData.taskUrgencyLevel] }}</text>
            </u-form-item>
            <u-form-item label="协同问题项" label-position="top" label-width="auto">
              <view>
                <view
                  class="group-tag"
                  v-for="(item, index) of coordTypeList"
                  :key="index"
                >
                  <view class="group-name">{{ item.coordTypeName }}</view>
                  <view class="group-tag-list">
                    <u-tag
                      v-for="tagItem of item.tags.filter(item => !!item)"
                      :text="tagItem.text"
                      :key="tagItem.value"
                      style="margin: 0 20rpx 20rpx 0; padding: 18rpx 22rpx; font-size: 28rpx;"
                    />
                  </view>
                </view>
              </view>
            </u-form-item>
            <u-form-item label="备注说明" label-position="top">
              <u-input type="textarea" v-model="formData.taskNote" disabled />
            </u-form-item>
            <view>
              <upload-images
                :canAdd="false"
                :canDel="false"
                :url="uploadFile"
                :length="10"
                :extForm="{fiGroupCode: $FILE_GROUP_TYPE.three_teamwork_img, bizId: formData.taskUuid}"
                :bizId="formData.taskUuid"
                :del-url="delUrl"
                :can-add="true"
                :can-del="true"
                :renderImages="getImages($FILE_GROUP_TYPE.three_teamwork_img)"
                ref="saveModel3"
                style="padding-left: 0;"
              ></upload-images>
            </view>
          </u-form>
        </view>
      </u-card>

      <!-- 协同反馈 -->
      <template v-if="['03', '04', '05', '06', '07'].indexOf(formData.taskStatus) > -1">

        <view v-if="['03', '04'].indexOf(formData.taskStatus) > -1 && !isOperateAuth" style="text-align: center; margin: 30rpx 0; color: #999;">协同待反馈中...</view>

        <u-card v-else title="处理信息" style="margin-left: 0; margin-right: 0;">
          <view slot="body">
            <u-form :model="taskResultFormData">
              <u-form-item v-for="item of taskResultItem" :key="item.value" :label="item.text" :label-position="item.coordOperateType === '91404' ? 'top' : 'left'" label-width="auto">
                <!-- 文本框类型 -->
                <u-input v-if="item.coordOperateType === '91403'" placeholder="请输入处理结果" v-model="taskResultFormData[item.value]" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
                
                <!-- 是否单选框 -->
                <template v-if="item.coordOperateType === '91401'" >
                  <z-dict-radio :dictType="$u.dic.DIC_KEYS.S_SYS_YES_NO" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" v-model="taskResultFormData[item.value]" @input="handleRadioInput($event, item.value)"></z-dict-radio>
                </template>

                <!-- 字典选择器 -->
                <template v-if="item.coordOperateType === '91402'" >
                  <z-dict-select :dictType="item.contentOptions" :readOnly="!(['03', '04'].indexOf(formData.taskStatus) > -1)" v-model="taskResultFormData[item.value]"></z-dict-select>
                </template>
                
                <!-- 日期 -->
                <template v-if="item.coordOperateType === '91422'" >
                  <u-input placeholder="请选择日期" v-model="taskResultFormData[item.value]" disabled @click="handleDateClick(item.value, !(['03', '04'].indexOf(formData.taskStatus) > -1))" />
                  <u-icon slot="right" name="arrow-right"></u-icon>
                </template>

                <!-- 文本域 -->
                <u-input v-if="item.coordOperateType === '91404'" type="textarea" v-model="taskResultFormData[item.value]" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
                
              </u-form-item>
              
              <u-form-item label="案件信息" label-position="top" label-width="auto">
                <view style="padding-top: 12rpx; padding-bottom: 16rpx;">
                  <u-button v-if="['03', '04'].indexOf(formData.taskStatus) > -1 && isOperateAuth" type="primary" :plain="true" @click="handleAddCaseClick" style="display: inline-block;">立即立案</u-button>
                  <view class="case-list" style="margin-top: 15rpx; line-height: 48rpx;">
                    <case-info-item v-for="caseItem of caseList" :key="caseItem.caseUuid" :sealInfo="caseItem"></case-info-item>
                  </view>
                </view>
              </u-form-item>
              <u-form-item label="备注信息" label-position="top">
                <u-input type="textarea" v-model="taskResultFormData.resultRemark" :disabled="!(['03', '04'].indexOf(formData.taskStatus) > -1)" />
              </u-form-item>
            </u-form>
            <upload-images
              :canAdd="['03', '04'].indexOf(formData.taskStatus) > -1 && isOperateAuth"
              :canDel="['03', '04'].indexOf(formData.taskStatus) > -1"
              :url="uploadFile"
              :length="10"
              :extForm="{fiGroupCode: $FILE_GROUP_TYPE.three_teamwork_img_xtfk, bizId: formData.taskUuid}"
              :bizId="formData.taskUuid"
              :del-url="delUrl"
              :renderImages="getImages($FILE_GROUP_TYPE.three_teamwork_img_xtfk)"
              ref="saveModel3"
              style="padding-left: 0;"
            ></upload-images>
          </view>
        </u-card>

      </template>

      <!-- 审核 -->
      <template v-if="['05', '06', '07'].indexOf(formData.taskStatus) > -1">

        <view v-if="['05'].indexOf(formData.taskStatus) > -1 && !isOperateAuth" style="text-align: center; margin: 30rpx 0; color: #999;">协同待审核中...</view>

        <u-card v-else  title="审核信息" style="margin-left: 0; margin-right: 0;">
          <view slot="body">
            <u-form :model="approvalFormData">
              <u-form-item label="审核意见" label-position="top">
                <u-input type="textarea" v-model="approvalFormData.approveRemark" :disabled="!(formData.taskStatus == '05' && isOperateAuth)" />
              </u-form-item>
            </u-form>
          </view>
        </u-card>
      </template>
      
      <u-card title="审批历史" style="margin-left: 0; margin-right: 0;">
        <view slot="body" style="padding: 0 20rpx;">
          <flow-his-no-doc :bizUuid="formData.taskUuid" :processDefKey="flowCode" :endTitle="formData.taskStatus === '07' ? '结束' : ''"></flow-his-no-doc>
        </view>
      </u-card>

    </view>

    <template v-if="isOperateAuth">
      <!-- 派发/转办 -->
      <view v-if="formData.taskStatus == '02'" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="primary" @click="handleAudit('01', 'xtpf')">派发</u-button>
        <u-button class="u-btn" type="success" @click="handleAudit('01', 'xtzb')">转办</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>

      <!-- 协同反馈 -->
      <view v-if="['03', '04'].indexOf(formData.taskStatus) > -1" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="primary" @click="handleSaveTaskResult">保存</u-button>
        <u-button class="u-btn" type="success" @click="handleAudit('01')">提交</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>

      <!-- 协同审核 -->
      <view v-if="['05'].indexOf(formData.taskStatus) > -1" class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="success" @click="handleAudit('01')">提交</u-button>
        <u-button class="u-btn" type="error" @click="handleAudit('03')">退回</u-button>
      </view>
    </template>

    <!-- 案件类型 -->
    <u-action-sheet :list="caseTypeList" v-model="caseActionShow" @click="handleCaseActionClick"></u-action-sheet>

    <u-modal
      title="提示"
      :show-cancel-button="true"
      cancel-text="取消"
      v-model="flowReturnShow"
      @confirm="handleFlowReturnConfirm"
      content="确认退回吗？"
    />

    <!-- 日期选择器 -->
    <u-picker v-if="datePickerShow" mode="time" v-model="datePickerShow" :default-time="taskResultFormData[currSelCoordType]" :params="timeParams" @confirm="handleDatePickerConfirm"></u-picker>
  </view>
</template>

<script>
import commonService from '@/service/eCigar/common.service';
import intelligenceservice from "@/service/intelligence/intelligence.service";
import threeTeamworkService from "@/service/threeTeamwork/three.teamwork.service.js";
import clientItem from "./components/client-item.vue";
import { UploadImages } from "@/components";
import {
  CASE_TYPE,
} from '@/service/case/mapping/index.js';
import caseInfoItem from './components/caseInfoItem.vue';
import { ZDictRadio, ZDictSelect } from '@/components';
import flowHisNoDoc from "@/components/flow-his-no-doc.vue";
import fsection from "@/components/form-section.vue";


const allTaskUrgencyLevel = {
  "01": "一般",
  "02": "紧急",
  "03": "特急"
};

export default {
  components: {
    clientItem,
    UploadImages,
    caseInfoItem,
    ZDictRadio,
    ZDictSelect,
    fsection,
    flowHisNoDoc
  },
  data() {
    return {
      flowCode: "coordinationTask", // 流程编码
      user: this.$store.state.userInfo,
      loading: true,
      formData: {},
      allTaskUrgencyLevel,
      retailerList: [],
      allBusinessList: [], // 所有业务指标
      filePath: [],
      flowHandleInfo: {},

      // 协同反馈处理信息
      taskResultFormData: {
        resultRemark: ""
      },

      // 审核信息
      approvalFormData: {},

      uploadFile: commonService.uploadFile,
      delUrl: commonService.deleteFile,

      flowReturnShow: false,

      caseTypeList: [{
        text: "简易案件"
      }, {
        text: "一般案件"
      }],
      caseActionShow: false,
      caseList: [],

      timeParams: {
				year: true,
				month: true,
				day: true,
				hour: false,
				minute: false,
				second: false
			},
      currSelCoordType: "",
      datePickerShow: false,
    };
  },
  computed: {
    coordTypeList() {
      let currBusinessList = this.allBusinessList.filter(item => item.businessType == this.formData.businessType);

      let currCoordTypeList = [];
      let itemUuids = this.formData.itemUuidArray || [];

      if (currBusinessList.length) {
        currCoordTypeList = currBusinessList[0].coordTypeList.map(coordTypeItem => {
          coordTypeItem.tags = coordTypeItem.coordItemList.map(coordItem => {
            if(itemUuids.indexOf(coordItem.itemUuid) > -1) {
              return { text: coordItem.itemName, value: coordItem.itemUuid , ...coordItem }
            }
            
          })
          return coordTypeItem;
        })
      }

      currCoordTypeList = currCoordTypeList.map(item => {
        if (item.tags) {
          item.tags = item.tags.filter(item => !!item);
        }
        return item;
      });
      currCoordTypeList = currCoordTypeList.filter(item => item.tags && item.tags.length);

      return currCoordTypeList;
    },
    taskResultItem() {
      let list = [];
      this.coordTypeList.map(item => {
        item.tags.map(tagItem => {
          list.push(tagItem);
        });
      });
      return list;
    },
    // 是否具有页面操作权限
    isOperateAuth() {
      let flag = false;

      let handlePersonUuids = this.formData.handlePersonUuids || "";
      if (handlePersonUuids.indexOf(this.user.user.personUuid) > -1) {
        flag = true;
      }
      return flag;
    },
  },
  onLoad(options) {
    let routeParams = this.getRouteParam();
    if (options.taskUuid) {
      this.formData.taskUuid = options.taskUuid;
    } else if (routeParams.taskUuid) {
      this.formData.taskUuid = routeParams.taskUuid;
    }

    this.getMSCoordinationTaskInfo(this.formData.taskUuid);
    this.getCoordinationTaskItem();
    if (!!this.formData.taskUuid) {
      this.getTaskCaseList();
    }
  },
  methods: {
    handleAddCaseClick() {
      this.caseActionShow = true;
    },
    handleCaseActionClick(index) {
      this.$u.route({
        url: '/pages/case/components/caseFilingLink',
        type: 'to',
        params: {
          caseType: index === 0 ? CASE_TYPE.SIMPLE : CASE_TYPE.NORMAL,
          from: "threeTeamwork"
        },
      });
    },
    // 获取任务详情
    getMSCoordinationTaskInfo(taskUuid) {
      this.$modal.showLoading('加载中...');
      let paras = { taskUuid };
      this.loading = true;
      threeTeamworkService.getMSCoordinationTaskInfo(paras).then(res => {
        this.$modal.hideLoading();
        this.loading = false;
        if (res.success) {
          if(!taskUuid) {
            this.formData = {...res.bean};
          } else {
            // 详情
            const { licenseList, tasklist, taskResultList, approveResult } = res.bean;
            this.retailerList = [licenseList];

            this.formData = { ...tasklist };

            // 协同反馈处理信息
            // if (tasklist) {}
            let defaultTaskResultFormData = {};
            tasklist.itemUuidArray.map(item => {
              defaultTaskResultFormData[item] = "";
            });
            let taskResultData = taskResultList || {};
            this.taskResultFormData = { ...this.taskResultFormData, ...defaultTaskResultFormData, ...taskResultData };

            // 审核信息
            if (approveResult) {
              this.approvalFormData = { ...approveResult, approveRemark: approveResult.approveResult };
            }
          }
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("数据获取失败!");
        this.$modal.hideLoading();
      });
    },
    // 获取所有指标类型
    getCoordinationTaskItem() {
      threeTeamworkService.getCoordinationTaskItem({
        taskUuid: this.formData.taskUuid
      }).then(res => {
        if (res.success) {
          this.allBusinessList = res.data;
        } else {
          this.$u.toast(res.msg);
        }
      });
    },
    getImages(fileGroup) {
      return () => new Promise((res, rej) => {
        this.renderImages(fileGroup).then(data => {
          res(data)
        }).catch(() => {
          rej([])
        })
      });
    },
    renderImages(fileGroup){
      return new Promise((res, rej) => {
        intelligenceservice.findFilesByBizIdAndGroup({
          bizId: this.formData.taskUuid,
          group: fileGroup,
        }).then(r => {
					if(r.code == 200 && r.success && Array.isArray(r.data)) {
						r.data.forEach(i => {
							i.src = `${commonService.baseUrl}/commonfile/filestore/downloadFile.do?fileId=${i.gfiId}&tk=${uni.getStorageSync("tk")}`;
              i.filePath = i.src;
						});
						res(r.data);
					} else {
					 res([]);
					}
				});
			})
    },
    updateBackState(param) {
      if (param["flowUserSelectBack"]) {
        // 审核人员选择回调
        let nextPersonUuids = param["flowUserSelectBack"].map(item => item.personId).join(",");

        this.flowHandleInfo.nextPersonUuids = nextPersonUuids;
        let params = { ...this.flowHandleInfo };

        if (["02"].indexOf(this.formData.taskStatus) > -1) {
          // 协同派发/转办
          params.remark = params.operationType === "xtzb" ? "协同转办" : "协同派发";
        } else if (["03", "04"].indexOf(this.formData.taskStatus) > -1) {
          // 协同反馈
          const checkResultParams = this.getTaskResultFormData();
          params = { ...params, ...checkResultParams };

        }

        this.auditCoordinationTask(params);
      } else if (param["createCaseSuccess"]) {
        let caseData = param["createCaseSuccess"];
        // 立案成功后的回调
        this.bindCase(caseData.caseUuid, () => {
          this.getTaskCaseList();
        });
      }
    },

    // 获取协同反馈表单数据
    getTaskResultFormData() {
      // 协同反馈
      let resultInfo = JSON.parse(JSON.stringify(this.taskResultFormData));
      let tasksResultList = [];
      for (let key in resultInfo) {
        if (["resultRemark"].indexOf(key) < 0) {
          tasksResultList.push({itemUuid: key, checkResult: resultInfo[key] });
          delete resultInfo[key];
        }
      }
      resultInfo.tasksResultList = tasksResultList;

      return { ...resultInfo, taskUuid: this.formData.taskUuid, taskStatus: this.formData.taskStatus };
    },
    
    // 验证协同反馈表单内容
    validTaskResultForm() {
      let taskResultFormData = this.getTaskResultFormData();
      let checkResultFlag = true;

      for (let i=0; i<taskResultFormData.tasksResultList.length; i++) {
        if (!taskResultFormData.tasksResultList[i].checkResult) {
          checkResultFlag = false;
        }
      }
      if (!checkResultFlag) {
        this.$u.toast("处理项结果不能为空!");
        return false;
      } else if (!taskResultFormData.resultRemark) {
        this.$u.toast("备注信息不能为空!");
        return false;
      }
      return taskResultFormData;
    },
    // 协同反馈保存按钮
    handleSaveTaskResult() {
      this.saveCoordinationTaskResult();
    },
    // 保存任务处理结果
    saveCoordinationTaskResult() {
      const params = this.validTaskResultForm();
      
      if (params) {
        this.$modal.showLoading("数据保存中...");
        threeTeamworkService.saveCoordinationTaskResult(params).then(res => {
          if (res.success) {
            this.$u.toast("数据保存成功!");
          } else {
            this.$u.toast(res.msg);
          }
        }).catch(() => {
          this.$u.toast("数据保存失败!");
        })
      }
    },

    // 获取流程获选人参数
    getNextFlowUsersExtData() {
      this.$modal.showLoading("获取候选人中...");
      threeTeamworkService.getNextFlowUsersExtData({
        taskUuid: this.formData.taskUuid,
        operationType: this.flowHandleInfo.operationType
      }).then(res => {
        if (res.success) {
          let extParams = res.bean || {};
          this.setRouteParam({
            ...extParams
          });
          this.$u.route({
            url: "/pages/commonPage/flowUserSelectComponent",
            params: {
              flowFormCode: this.flowCode,
              // docInsUuid: this.formData.taskUuid
            }
          });
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("候选人获取失败!");
      })
    },
    /**
     * 处理流程审批
     * @param {*} approveResult 审核类型 01(审核)、03(退回)
     * @param {*} operationType 转办：xtzb  派发：xtpf
     */
    handleAudit(approveResult, operationType) {
      this.flowHandleInfo.approveResult = approveResult;
      this.flowHandleInfo.operationType = operationType;

      if (approveResult === "01") {
        if (["03", "04"].indexOf(this.formData.taskStatus) > -1) {
          // 协同反馈
          if (this.validTaskResultForm()) {
            this.getNextFlowUsersExtData();
          }
          return;
        } else if (this.formData.taskStatus == "05") {
          // 协同审核
          if (!this.approvalFormData.approveRemark) {
            this.$u.toast("请输入审核意见!");
            return;
          }
          let params = { ...this.flowHandleInfo, ...this.approvalFormData };
          this.auditCoordinationTask(params);
        } else {
          this.getNextFlowUsersExtData();
        }
      } else {
        // 退回
        this.flowReturnShow = true;
      }
    },
    // 退回模态框确认回调
    handleFlowReturnConfirm() {
      this.auditCoordinationTask(this.flowHandleInfo);
    },
    /**
     * 流程审批
     * @param {*} params // 流程处理信息
     */
    auditCoordinationTask(params) {
      this.$modal.showLoading('流程提交中...');
      threeTeamworkService.auditCoordinationTask({
        taskUuid: this.formData.taskUuid,
        taskStatus: this.formData.taskStatus,
        ...params,
      }).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast("操作成功!");
          setTimeout(() => {
            this.backPrev({
              paramKey: "submitSuccess",
              param: true
            });
          }, 1000);
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("操作失败!");
        this.$modal.hideLoading();
      })
    },
    /**
     * 绑定案件信息
     */
    bindCase(caseUuid, successCallback) {
      this.$modal.showLoading('案件绑定中...');
      threeTeamworkService.saveCoordinationTaskCase({
        taskUuid: this.formData.taskUuid,
        caseUuid
      }).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast("绑定成功!");
          successCallback && successCallback();
        } else {
          this.$u.toast(res.msg);
        }
      }).catch(() => {
        this.$u.toast("绑定失败!");
        this.$modal.hideLoading();
      })
    },
    /**
     * 查询任务绑定的案件列表
     */
    getTaskCaseList() {
      threeTeamworkService.queryRecordCaseList({
        taskUuid: this.formData.taskUuid
      }).then(res => {
        if(res.success) {
          this.caseList = res.data;
        }
      });
    },
    handleDateClick(type, disabled) {
      if (disabled) {
        return;
      }
      this.datePickerShow = true;
      this.currSelCoordType = type;
    },
    handleDatePickerConfirm(e) {
      this.taskResultFormData[this.currSelCoordType] = `${e.year}-${e.month}-${e.day}`;
    },
    handleRadioInput(e, coordType) {
      this.taskResultFormData[coordType] = e;
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 0;
}
.content {
  background-color: #f3f4f5;
}

.card {
  margin-left: 0;
  margin-right: 0;
  border-radius: 0;
  padding-left: 25rpx;
  padding-right: 25rpx;
}

.group-tag {
  .group-name {
    font-size: 30rpx;
    font-weight: 600;
    margin: 20rpx 0 18rpx;
  }
}
</style>